package com.zmn.plat.admin.controller.product;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.plat.model.entity.product.ServProduct;
import com.zmn.plat.model.vo.product.ServProductCopyVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.plat.common.constant.ProductConsts;
import com.zmn.plat.manager.dictionary.ProductDict;
import com.zmn.plat.common.exception.PlatException;
import com.zmn.plat.model.vo.product.ServProductBackVO;
import com.zmn.plat.model.vo.product.ServProductDescVO;
import com.zmn.plat.model.vo.product.ServProductVO;

/**
 * 描述: 产品管理修改控制
 *
 * @author tanbiao
 * @since: 2018/11/5 22:06
 */
@Controller
@RequestMapping("/showProduct/")
public class ShowServProductModifyController extends ServProductBaseController {

    private Logger logger = LoggerFactory.getLogger(ShowServProductModifyController.class);

    /**
     * region 新增/修改
     *
     * @param servProductVO
     *            产品新增修改实体
     * @return ModelAndView 执行结果
     * @author tanbiao
     * @since 15:38 2019/9/22
     */
    @RequestMapping(value = "addEdit")
    @ResponseBody
    @SuppressWarnings("Duplicates")
    public ResponseDTO addEdit(HttpServletRequest request, @RequestBody ServProductVO servProductVO) {
        String lable = "新增产品";

        servProductVO.setShowType(ProductConsts.EC_PRODUCT_TYPE);
        try {
            String userName = getMcStaffRealName();
            if (servProductVO.getProductId() == null) {
                lable = "新增产品";
                String creater = getMcStaff().getRealName();
                servProductVO.setSort(servProductVO.getShowSort());
                Integer flag = servProductBService.insertAll(servProductVO, creater);
                return transAddFlagToMessage(flag);
            } else {
                lable = "修改产品";
                if (Objects.equals(ProductDict.STATUS_ENABLE, servProductVO.getStatus()) && Objects.equals(GlobalConsts.NO, servProductVO.getDefaultType())) {
                    List<Integer> idList = new ArrayList<>(1);
                    idList.add(servProductVO.getProductId());
                    List<ServProductBackVO> relationProducts = servProductService.listProductHasRelatedForShow(idList);
                    if (!CollectionUtils.isEmpty(relationProducts)) {
                        return ResponseDTO.fail("前台产品上架必须关联至少一个上架的后台产品；并且不能间接关联多个后台一级产品");
                    }
                }
                servProductVO.setSort(servProductVO.getShowSort());
                Integer flag = servProductBService.updateAll(servProductVO, userName);
                return transModifyFlagToMessage(flag);
            }
        } catch (PlatException e) {
            return ResponseDTO.fail(e.getMessage());
        } catch (Exception ex) {
            logger.error(lable + "失败", ex);
            return ResponseDTO.fail(lable + "失败！");
        }
    }

    /**
     * 添加产品描述
     *
     * @param request
     * @param servProductDescVO
     * @return
     * @author tanbiao
     * @since 15:38 2019/9/22
     */
    @RequestMapping(value = "addEditDesc")
    @ResponseBody
    public ResponseDTO addEdit(HttpServletRequest request, @RequestBody ServProductDescVO servProductDescVO) {
        return super.addEdit(getMcStaffRealName(), servProductDescVO);
    }

    /**
     * 描述:修改产品状态
     *
     * @param ids
     *            产品ID组成的字符串 eg: productId1,productId2
     * @param status
     *            修改的状态
     * @return: com.zmn.common.dto2.ResponseDTO 执行结果
     * @auther: tanbiao
     * @since: 2018/11/5 22:39
     */
    @SuppressWarnings("Duplicates")
    @RequestMapping(value = "updateStatus")
    @ResponseBody
    public ResponseDTO updateStatus(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "ids", defaultValue = "") String ids, @RequestParam(value = "status", defaultValue = "0") int status) {

        if (StringUtil.isBlank(ids)) {
            return ResponseDTO.fail("请选择要更改状态的产品！");
        }

        List<Integer> productIds = StringUtil.convertStrsToList(ids);

        List<ServProduct> products = servProductService.listByIdList(productIds);
        // 前台默认产品上下架不需要判断，过滤出非前台默认产品
        List<Integer> notDefaultProductIds = products.stream().filter(e -> Objects.equals(GlobalConsts.NO, e.getDefaultType())).map(e -> e.getProductId()).collect(Collectors.toList());

        // 前台产品上架 需要判断是否关联后台产品，如果没有则提示“前台产品上架必须关联至少一个上架的后台产品”；20191023
        if (ProductDict.STATUS_ENABLE == status) {
            if (!CollectionUtils.isEmpty(notDefaultProductIds)) {
                List<ServProductBackVO> relationProducts = servProductService.listProductHasRelatedForShow(productIds);
                if (!CollectionUtils.isEmpty(relationProducts)) {
                    StringBuilder stringBuilder = new StringBuilder();
                    relationProducts.forEach(e -> stringBuilder.append(e.getProductId()).append(","));
                    stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                    return ResponseDTO.fail("前台产品[" + stringBuilder.toString() + "]上架必须关联至少一个上架的后台产品！");
                }
            }
        }

        try {
            servProductBService.updateStatusBatch(productIds, status, getMcStaffRealName(), ProductConsts.EC_PRODUCT_TYPE);
        } catch (PlatException e) {
            return ResponseDTO.fail(e.getMessage());
        }

        return ResponseDTO.success(true,"操作成功！");
    }

    /**
     * 描述:前端产品修改排序
     *
     * @param productId
     *            产品id
     * @param sort
     *            修改的状态
     * @return: com.zmn.common.dto2.ResponseDTO 执行结果
     * @auther: tanbiao
     * @since: 2018/11/5 22:39
     */
    @RequestMapping(value = "updateSort")
    @ResponseBody
    public ResponseDTO updateSort(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "id", defaultValue = "0") Integer productId, @RequestParam(value = "sort", defaultValue = "0") Integer sort) {

        if (productId == 0) {
            return ResponseDTO.fail("请选择要更改排序的产品！");
        }
        if (sort == 0) {
            return ResponseDTO.fail("请设置产品排序值！");
        }

        servProductService.updateShowSortByKey(productId, sort, getMcStaffRealName());
        return ResponseDTO.success(true,"操作成功！");
    }

    @RequestMapping(value = "copyFromProduct")
    @ResponseBody
    public ResponseDTO copyFromProduct(HttpServletRequest request, HttpServletResponse response,
                                  @RequestBody ServProductCopyVO servProductCopyVO){
        try{
            servProductCopyVO.setOpeator(getMcStaffRealName());
            Integer result = servProductBService.copyFromProduct(servProductCopyVO);
            return ResponseDTO.success(result,"复制成功");
        }catch (PlatException e){
            return ResponseDTO.fail(e.getMessage());
        }catch (Exception e){
            logger.error("copyFromProduct error.",e);
            return ResponseDTO.fail(GlobalConsts.FAILD_MSG);
        }

    }
}
